package com.baikeyang.bike.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baikeyang.bike.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baikeyang.bike.bean.BikeBean;
import com.baikeyang.bike.bean.UserAgent;
import com.baikeyang.bike.service.IXABikeService;
import com.baikeyang.bike.service.impl.XABikeServiceImpl;

@Controller("bikeController")
@Scope(value="request")
@RequestMapping("/")
public class BikeController extends BaseController {
	
	private static Logger log = Logger.getLogger(BikeController.class);
	
	@Autowired
	private IXABikeService xaBikeService;
	
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap map){
		UserAgent ua = UserAgentUtil.getUserAgent(request.getHeader("User-Agent"));
		if(null != ua && 
				(ua.getPlatformType().equals("Windows Phone") || ua.getPlatformType().equals("IOS"))
				){// 只允许Windows Phone 和 iPhone 终端访问
			return new ModelAndView("index");
		}
		map.put("ua", ua);
		return new ModelAndView("message");
	}

	/**
	 * 获取异常站点信息
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getAbnormalSite", method = {RequestMethod.POST,RequestMethod.GET})
	public String getBikeAllAbnormalSite(String type){
		int convertType = 0;// default : 0 (百度); 1:腾讯; 2:高德
		try {
			convertType = Integer.parseInt(type);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		List<BikeBean> bikes = xaBikeService.getBikeAbnormalSite();
		bikes = xaBikeService.bikeLocalConvert(bikes,null,convertType);
		return parse2JsonArr(bikes);
	}
	
	/**
	 * 获取正常站点信息
	 * @param request
	 * @param response
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getNormalSite", method = {RequestMethod.POST,RequestMethod.GET})
	public String getBikeAllNormalSite(HttpServletRequest request, HttpServletResponse response, String type){
		int convertType = 0;// default : 0 (百度); 1:腾讯; 2:高德
		try {
			convertType = Integer.parseInt(type);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		List<BikeBean> bikes = xaBikeService.getBikeNormalSite();
		bikes = xaBikeService.bikeLocalConvert(bikes,null,convertType);
		return parse2JsonArr(bikes);
	}
	
	/**
	 * 同步站点信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "synchronize", method = {RequestMethod.POST, RequestMethod.GET}, produces = { "application/json;charset=UTF-8" })
	public String synchronizeBikeSite(){
		xaBikeService.synchronizeBikeSite();
		return parse2Json("SUCCESS");
	}
	
	/**
	 * 获取站点详情信息
	 * @param request
	 * @param response
	 * @param siteId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "get/site/{siteId}", method = {RequestMethod.POST, RequestMethod.GET}, produces = { "application/json;charset=UTF-8" })
	public String getBikeSite(HttpServletRequest request, HttpServletResponse response, @PathVariable("siteId")String siteId){
		return parse2Json(xaBikeService.getBikeSiteById(siteId));
	}
	
	/**
	 * 获取租车记录
	 * @param cardNo
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "get/record/{cardNo}", method = {RequestMethod.POST, RequestMethod.GET}, produces = { "application/json;charset=UTF-8" })
	public String getBikeRecord(@PathVariable("cardNo")String cardNo) throws Exception{
		String str = xaBikeService.findBikeTradeRecords(cardNo);
		return str;
	}
	
	/**
	 * 根据经纬度获取周围站点
	 * @param lng 经度
	 * @param lat 纬度
	 * @param radius 半径
	 * @param type 经纬度纠偏类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getSearch", method = {RequestMethod.POST,RequestMethod.GET},  produces = "application/json; charset=utf-8") 
	public String getSearchByLocalPosition(String lng, String lat, String radius, String type){
		double cenLngX = 0;
		double cenLatY = 0;
		int convertType = 2;// default : 0 (百度); 1:腾讯; 2:高德
		try {
			cenLngX = Double.parseDouble(lng);
			cenLatY = Double.parseDouble(lat);
			convertType = Integer.parseInt(type);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		List<BikeBean> result = new ArrayList<BikeBean>();
		// TODO 获取所有车辆
		List<BikeBean> bikes = xaBikeService.getAllBikePostions(convertType);
//		bikes = bikeLocalConvert(bikes,null,convertType);
		for (int i = 0; i < bikes.size(); i++) {
			BikeBean bike = bikes.get(i);
			if(null != bike){
				if(StringUtil.isNotEmpty(bike.getLongitude()) && StringUtil.isNotEmpty(bike.getLatitude())
						&& StringUtil.isNotEmpty(lng) && StringUtil.isNotEmpty(lat)){
					double bikeLngX = 0;
					double bikeLatY = 0;
					double bikeRadius = 0;
					try {
						bikeLngX = Double.parseDouble(bike.getLongitude());
						bikeLatY = Double.parseDouble(bike.getLatitude());
						bikeRadius = Double.parseDouble(radius);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
					// 判断车辆是否在区域内
					if (MapUtil.isPointInCircleArea(bikeLngX, bikeLatY, cenLngX, cenLatY, bikeRadius)) {
						result.add(bike);
					}
				}
			}
		}
		//result = xaBikeService.bikeLocalConvert(result,null,convertType);
		return parse2JsonArr(result);
	}

	/**
	 * 搜索地理位置
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "searchAddress", method = {RequestMethod.POST,RequestMethod.GET},  produces = "application/json; charset=utf-8")
	public String searchLocaltion(HttpServletRequest request, HttpServletResponse response,
								  String address){
		String result = "";
		if(StringUtil.isNotEmpty(address)){
			String key = PropertiesUtil.getValue("map.qq.key");
			String region = "西安";//设置城市名，限制关键词所示的地域范围，如，仅获取“广州市”范围内的提示内容
			String httpUrl = "http://apis.map.qq.com/ws/place/v1/suggestion";
			String region_fix = "1";//0：[默认]当前城市无结果时，自动扩大范围到全国匹配 1：固定在当前城市
			Map<String, String> parameterMap = new HashMap<String, String>();
			parameterMap.put("region", region);
			parameterMap.put("key", key);
			parameterMap.put("keyword", address);
			parameterMap.put("region_fix", region_fix);
			result = HttpClientUtils.doGet(httpUrl, parameterMap);
		}
		return result;
	}
	
	public static void main(String[] args) {
//		StringBuffer sb = new StringBuffer("34.1964,108.911102;34.196497,108.910909;"
//				+ "34.214562,108.905103;34.217674,108.90805;34.206242,108.91492;34.20448,"
//				+ "108.926306;34.204003,108.923171;34.204081,108.923773;34.204335,108.920022;"
//				+ "34.204081,108.918073;34.217482,108.919299;34.217463,108.923153;34.209712,"
//				+ "108.926046;34.214093,108.920781;34.214131,108.923503;34.207343,108.926252;"
//				+ "34.217478,108.92314;34.214418,108.926234;34.214064,108.918208;34.213955,108.915612;"
//				+ "34.207361,108.92601;34.206895,108.92601;34.204454,108.925569;34.199155,108.92601;"
//				+ "34.204012,108.900033;34.211427,108.919415;34.210853,108.916015;34.205904,108.908393;"
//				+ "34.204244,108.905172;34.214002,108.911537;34.209263,108.906929;");
//		ConvertLocalReuslt result = convertLocalQQMapByBaidu(sb);
//		System.out.println(result);

	}
	
	
	
}
